package com.young.statemachine.service;

import com.young.statemachine.domain.Work;
import com.young.statemachine.enums.WorkEvents;
import com.young.statemachine.enums.WorkStates;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @className: WorkService
 * @author: Young
 * @date: 2025/1/15 23:29
 * @Version: 1.0
 * @description:
 */
@Slf4j
@Service
public class WorkService {

    private final StateMachine<WorkStates, WorkEvents> stateMachine;

    public WorkService(StateMachine<WorkStates, WorkEvents> stateMachine) {
        this.stateMachine = stateMachine;
    }

    public void reached(String sn) {
        Work work = new Work();
        work.setSn("1234565");
        work.setRes("ok");
        work.setTime(new Date());
        Message<WorkEvents> message = MessageBuilder.withPayload(WorkEvents.REACHED).setHeader("work", work).build();
        if (!stateMachine.sendEvent(message)){
            log.error("线程：{}，状态异常",Thread.currentThread().getName());
        }
    }
}
